ApplicaitonContext的额外功能依赖于bean的后置处理器
可以利用监听器完成定时器的开关
// 引入定时器
@EnableScheduling
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class);
}
}
@Component(value = TaskScheduled.TASK)
public class TaskScheduled {
public static final String TASK = "taskScheduled";
@Autowired
private ApplicationContext applicationContext;
private AtomicInteger num = new AtomicInteger(0);
@Scheduled(cron = "*/5 * * * * ?")
public void task(){
System.out.println("doing task...");
// 自定义条件,条件满足之后启动或者停止监听器
if(num.incrementAndGet() == 3){
// 发布任务
applicationContext.publishEvent(new DestroyEvent(applicationContext));
}
}
}
Event:
public class DestroyEvent extends ApplicationEvent {
public DestroyEvent(Object object){
super(object);
}
}
Listener:
@Component
public class DestroyListener implements ApplicationListener<DestroyEvent> {
@Override
public void onApplicationEvent(DestroyEvent destroyEvent) {
Object object = destroyEvent.getSource();
if(object instanceof ApplicationContext){
//AbstractApplicationContext 实现了 ApplicationContext
AbstractApplicationContext ap = (AbstractApplicationContext)object;
//DefaultListableBeanFactory 实现了 ConfigurableListableBeanFactory
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)ap.getBeanFactory();
// 如果工厂中有当前bean就销毁掉
if(beanFactory.containsBean(TaskScheduled.TASK)){
beanFactory.destroySingleton(TaskScheduled.TASK);
}
// 可以自定义再创建定时器
// beanFactory.createBean(TaskScheduled.class);
}
}
}